<template>
  <div>
    <!-- 面包屑导航区域！可以分装成为一个组件 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_option">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择器 -->
          <el-cascader v-model="selectedKeysArr"
                       :options="cateList"
                       :props="cascaderProps"
                       clearable
                       @change="cateChanged"></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs页签区域 -->
      <el-tabs v-model="activeName"
               @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数"
                     name="many">
          <!-- 添加参数的按钮 -->
          <el-button type="primary"
                     :disabled='isBtnDisabled'
                     size="mini"
                     @click="addDialogVisible=true">添加参数</el-button>
          <el-table :data="manyTableData"
                    border
                    stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <!-- 添加输入文本标签 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="tagInputRef"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <!-- 参数名称列 -->
            <el-table-column lable="参数名称"
                             prop="attr_name"></el-table-column>
            <!-- 操作列 -->
            <el-table-column lable="操作">
              <template slot-scope="scope">
                {{scope.attr_name}}
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="showEditDialog(scope.row.attr_id,scope.row)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性"
                     name="only">
          <!-- 添加属性的按钮 -->
          <el-button type="primary"
                     :disabled='isBtnDisabled'
                     size="mini"
                     @click="addDialogVisible=true">添加属性</el-button>
          <el-table :data="onlyTableData"
                    border
                    stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <!-- 添加输入文本标签 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="tagInputRef"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <!-- 属性名称列 -->
            <el-table-column lable="属性名称"
                             prop="attr_name"></el-table-column>
            <!-- 操作列 -->
            <el-table-column lable="操作">
              <template slot-scope="scope">
                {{scope.attr_name}}
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="showEditDialog(scope.row.attr_id,scope.row)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加'+titleText"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClosed">
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible=false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog :title="'编辑'+titleText"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editDialogClosed">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible=false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择器配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选中分类的Id数组
      selectedKeysArr: [],
      // 被激活的页签的名称
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加参数的验证数据对象
      addFormRules: {
        attr_name: [{
          required: true, message: '请输入参数名称', trigger: 'blur'
        }]
      },
      // 控制编辑对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑参数的表单数据对象
      editForm: {
        attr_name: ''
      },
      // 编辑参数的验证数据对象
      editFormRules: {
        attr_name: [{
          required: true, message: '请输入参数名称', trigger: 'blur'
        }]
      }
      // 控制按钮与文本框的切换显示
      // inputVisible: false,
      // 输入文本的内容
      // inputValue: ''
    };
  },
  created () {
    this.getCateList();
  },
  methods: {
    // 获取所有商品分类列表数据 给级联选择器
    async getCateList () {
      const { data: result } = await this.$http.get('categories')
      if (result.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.cateList = result.data;
    },
    // 级联选择器选择项发生变化事件
    async cateChanged () {
      // 判断选择的是否三级分类
      if (this.selectedKeysArr.length !== 3) {
        this.selectedKeysArr = [];
        this.manyTableData = [];
        this.onlyTableData = [];
      } else {
        // 根据所选分类的Id，和当前所处的面板，获取对应的参数
        const { data: result } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
        if (result.meta.status !== 200) return this.$message.error('获取列表参数失败！')
        result.data.forEach(item => {
          // 将字符串转换为数组并处理空字符串的问题
          item.attr_vals = item.attr_vals ? item.attr_vals = item.attr_vals.split(' ') : [];
          // 给对象添加文本框属性
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          // 动态添加this.$refs.tagInputRef.$set(val,'inputVisible',false)
          // 文本框中输入的值
          item.inputValue = ''
          // 动态添加this.$refs.tagInputRef.$set(val,'inputValue','')
        })
        if (this.activeName === 'many') {
          this.manyTableData = result.data;
        } else {
          this.onlyTableData = result.data;
        }
      }
    },
    // tab页签点击事件的处理函数
    handleTabClick () {
      this.cateChanged();
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      // 重置添加表单
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: result } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (result.meta.status !== 201) return this.$message.error('添加参数失败！')
        this.$message.success('添加参数成功！')
        this.addDialogVisible = false;
        this.cateChanged();
      })
    },
    // 点击按钮，展示编辑对话框
    // attrId不能为attr_id 需要在.eslintrc.js中添加rules规则中添加rules: {"camelcase": [0, { properties: 'always' }]}
    async showEditDialog (attrId, rowData) {
      // 拆分一下对象，不然当this.editForm数据发生改变的时候，scope.row也会发生改变即
      this.editForm = { ...rowData }
      console.log(this.editForm);
      // 查询当前参数的信息(没必要根据id查询行数据回显了)
      // const { data: result } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
      //   params: { attr_sel: this.activeName }
      // })
      // if (result.meta.status !== 200) return this.$message.error('获取参数信息失败')
      // this.editForm = result.data
      this.editDialogVisible = true;
    },
    // 监听编辑对话框的关闭事件
    editDialogClosed () {
      // 重置编辑表单
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮，编辑参数
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: result } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (result.meta.status !== 200) return this.$message.error('编辑参数失败！')
        this.$message.success('编辑参数成功！')
        this.editDialogVisible = false;
        this.cateChanged();
      })
    },
    // 根据Id删除对应的参数项
    async removeParams (attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 判断用户是否取消删除操作
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除!')
      // 删除的业务逻辑
      const { data: result } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (result.meta.status !== 200) return this.$message.error('删除删除失败！')
      this.$message.success('删除删除成功！')
      this.cateChanged();
    },
    // 新增文本框失去焦点，或按下了 Enter 键触发事件
    async handleInputConfirm (row) {
      // 清除空格空值的不合法内容
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        // 设置隐藏文本框
        row.inputVisible = false
        return;
      }
      // 如果输入了内容则发起添加请求
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = ''
      // 设置隐藏文本框
      row.inputVisible = false
      // 发起请求，保存这次数据
      this.saveAttrVals(row);
    },
    // 点击+ New Tag按钮显示添加文本框
    showInput (rowData) {
      // 设置显示文本框
      rowData.inputVisible = true
      // 设置文本框自动获取焦点
      // $nextTick方法的作用，就是当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        // 第一个$refs获得el-input组件 第二个$refs获得el-input组件上的原生input元素
        this.$refs.tagInputRef.$refs.input.focus();
      });
    },
    // 将对attr_vals的操作保存到数据库
    async saveAttrVals (row) {
      // 发起请求，保存这次数据
      const { data: result } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      console.log(result);
      if (result.meta.status !== 200) return this.$message.error('修改参数项失败！')
      this.$message.success('修改参数项成功!')
    },
    // 删除对应的参数可选项
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled () {
      if (this.selectedKeysArr.length !== 3) return true;
      return false;
    },
    // 当前选中的三级分类的Id
    cateId () {
      if (this.selectedKeysArr.length !== 3) return null;
      return this.selectedKeysArr[2]
    },
    // 共窗体计算窗体名
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang='less' scoped>
.cat_option {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
